#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import re

import openai

from utils.config import Config


class GPTUtil:
    __conversation_list = {}

    def __init__(self) -> None:
        config = Config()
        self.client = openai.OpenAI(
            api_key=config.OPEN_AI["api_key"],
            base_url=config.OPEN_AI["base_url"]
        )
        self.log = logging.getLogger(__name__)

    def get_answer(self, question: str, wxid: str) -> str:
        question = re.sub(r"@.*?[\u2005|\s]", "", question).replace(" ", "")
        # wxid或者roomid,个人时为微信id，群消息时为群id
        self.updateMessage(wxid, question, "user")
        self.log.info(f"{self.__conversation_list[wxid]}")
        rsp = self.getChatGPTAnswer(self.__conversation_list[wxid])
        self.updateMessage(wxid, rsp, "assistant")
        return rsp

    def getChatGPTAnswer(self, question):
        try:
            ret = self.client.chat.completions.create(

                model="gpt-4o",
                messages=question,
                temperature=0.2
            )
            rsp = ret.choices[0].message.content
        except Exception as e0:
            rsp = "发生未知错误：" + str(e0)
        return rsp

    def updateMessage(self, wxid: str, question: str, role: str) -> None:
        # 初始化聊天记录,组装系统信息
        if wxid not in self.__conversation_list.keys():
            question_ = [
                {"role": "system", "content": ""}
            ]
            self.__conversation_list[wxid] = question_

        # 将当前问题存储到上下文中
        content_question_ = {"role": role, "content": question}
        self.__conversation_list[wxid].append(content_question_)
        # 只存储10条记录，超过滚动清除
        i = len(self.__conversation_list[wxid])
        if i > 10:
            self.log.info("滚动清除微信记录：" + wxid)
            # 删除多余的记录，倒着删，且跳过第一个的系统消息
            del self.__conversation_list[wxid][1]
